<template>
  <div class="designer-container">
    <el-container>
      <el-header style="padding: 0">
        <el-menu
          default-active="BASE"
          class="designer-container-header-menu"
          mode="horizontal"
          @select="switchMenu"
        >
          <div>
            <el-button
              v-if="fullscreen"
              icon="arrow-left"
              circle
              @click="handleClose"
            >
            </el-button>
            <el-text>{{ formData ? formData.formName : "" }}</el-text>
          </div>
          <el-menu-item index="BASE">① 基础设置</el-menu-item>
          <el-menu-item index="FORM">② 表单设计</el-menu-item>
          <div>
            <el-button
              v-if="fullscreen"
              icon="Close"
              type="warning"
              round
              @click="handleClose"
              >关闭</el-button
            >
            <el-button
              icon="FolderChecked"
              type="primary"
              round
              @click="handleSave"
              >保存</el-button
            >
          </div>
        </el-menu>
      </el-header>
      <el-main
        :class="{
          'designer-container-main': true,
          'designer-container-main-fullscreen': fullscreen
        }"
      >
        <FormBaseSetting
          v-show="active === 'BASE'"
          ref="formbase"
          v-model:formData="formData"
        />
        <form-designer
          v-show="active === 'FORM'"
          ref="formdesign"
          v-model:formDef="formDef"
          v-model:formModel="formData"
          :fullscreen="props.fullscreen"
        />
      </el-main>
    </el-container>
    <DesignerValidate
      ref="processValidateRef"
      :validRefs="validRefs"
      :instance="_this"
      @success="handleValidSuccess"
    />
  </div>
</template>
<script setup name="FlowFormDesign" lang="ts">
import { ref, getCurrentInstance } from "vue";
import FormDesigner from "./FormDesigner.vue";
import FormBaseSetting from "./FormBaseSetting.vue";
import DesignerValidate from "../DesignerValidate.vue";
import { savePublish } from "@/api/flow/form/";
import { useMessage } from "@/hooks/message";
import type {
  DesignerRefs,
  DesignerRefItem,
  FormModel,
  FormDesignerModel,
  FormDesignerComponents
} from "./FormComponentMixin";

const props = defineProps({
  fullscreen: {
    type: Boolean,
    default: false
  }
});

const _this = getCurrentInstance();
const active = ref("BASE");
const processValidateRef = ref(null);
const formbase = ref(null);
const formdesign = ref(null);
const formModel = defineModel<FormModel>("formModel");
const formData = ref<FormModel>({
  id: "",
  formName: "未命名表单",
  formRemark: "",
  formStatus: "0",
  formInfo: "",
  formTypeId: "",
  formTypeCode: "",
  formTypeName: "",
  storageType: "0"
});

const validRefs = ref<DesignerRefs[]>([
  { _ref: "formbase", name: "基础设置", status: "" },
  { _ref: "formdesign", name: "表单设计", status: "" }
]);

const formDef = ref<FormDesignerModel>({
  conf: {
    labelPosition: "right", //标签位置
    labelWidth: 80, //标签宽度，
    size: "default"
  },
  components: [] as FormDesignerComponents[]
});

const emits = defineEmits(["closed"]);

watchEffect(() => {
  if (formModel.value) {
    formData.value = formModel.value;
    if (formModel.value.formInfo) {
      try {
        const formDefJson = JSON.parse(formModel.value.formInfo);
        if (formDefJson.conf && formDefJson.components) {
          formDef.value = formDefJson;
        } else {
          formDef.value = {
            conf: {
              labelPosition: "right", //标签位置
              labelWidth: 80, //标签宽度，
              size: "default"
            },
            components: []
          };
        }
      } catch (err) {
        formDef.value = {
          conf: {
            labelPosition: "right", //标签位置
            labelWidth: 80, //标签宽度，
            size: "default"
          },
          components: []
        };
      }
    }
  }
});

function switchMenu(index) {
  if (active.value === "BASE") {
    const ref = _this.refs[validRefs.value[0]._ref] as DesignerRefItem;
    ref
      .validate()
      .then(res => {
        active.value = index;
      })
      .catch(err => {
        active.value = "BASE";
        return false;
      });
  } else {
    active.value = index;
  }
}

const saveOrPublish = () => {
  formData.value.formInfo = JSON.stringify(formDef.value);
  savePublish(formData.value)
    .then(res => {
      if (res.code === 200) {
        useMessage().success("保存成功");
        emits("closed");
      } else {
        useMessage().error(res.msg);
      }
    })
    .catch(err => {
      useMessage().error("保存失败");
    });
};

function handleSave() {
  processValidateRef.value
    .validate()
    .then(() => {
      processValidateRef.value.reloadValidResult(true);
    })
    .catch(errs => {
      processValidateRef.value.reloadValidResult(false);
      const validIndex = processValidateRef.value.getValidIndex();
      validRefs.value[validIndex].status = "error";
      if (Array.isArray(errs)) {
        processValidateRef.value.addValidResult(errs);
      }
    });
}

const handleValidSuccess = () => {
  saveOrPublish();
};

const handleClose = () => {
  emits("closed");
};
</script>
<style lang="scss" scoped>
.designer-container {
  background: $main-bgc;
  overflow-y: hidden;

  .el-header {
    height: 60px !important;
  }

  .designer-container-header-menu {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    background: white;

    & > div:first-child {
      position: absolute;
      left: 20px;
      display: flex;
      align-items: center;
    }

    & > div:last-child {
      position: absolute;
      right: 20px;
    }
  }

  .designer-container-main {
    height: 100%;
    width: 100%;
    padding: 0px !important;
    margin: 0 auto;
    overflow: hidden;
  }

  .designer-container-main-fullscreen {
    height: calc(100vh - 70px) !important;
  }

  .w-no-padding {
    padding: 0;
  }
}
</style>
